package com.ouheng.wxpay;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;




/** 
 * @author: py
 * @version:2017年1月10日 上午11:17:59 
 * qwy.wx.wxpay.util.WXPayRefundUtil.java
 * @Desc  微信退款 申请以及退款
 * //api地址：http://mch.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_4
 */
public class WXPayRefundUtil {

	static String  appid = "wxb7eef9068526ea2f"; //微信公众号apid
	static String appsecret = "f3a95fc1a496c04b6a2219c5a987c474"; //微信公众号appsecret
	public static String mch_id = "1501856881";  //微信商户id
	static String op_user_id = "001 ";//操作员帐号, 默认为商户号
	static String partnerkey = "TwHFblP18E9jFOPJ6EvC2Ht3n6o166R7";//商户平台上的那个KEY
	/**
	 * @date 2017年1月10日上午10:36:50 void
	 * @Des:退款
	 */
	public static Boolean wechatRefund(WXPayRefundVo wXPayRefundVo) {
		// 商户系统内部的退款单号，商户系统内部唯一，同一退款单号多次请求只退一笔//20180704154601hctrvic45gu8ewmp9x
		String out_refund_no = wXPayRefundVo.getOut_refund_no();
		String out_trade_no = wXPayRefundVo.getOut_trade_no();// 商户侧传给微信的订单号
		
		Long total_fee_long=(wXPayRefundVo.getTotal_fee().multiply(new BigDecimal(100))).longValue();
		
		Long refund_fee_long=(wXPayRefundVo.getRefund_fee().multiply(new BigDecimal(100))).longValue();
		
		String total_fee = String.valueOf(total_fee_long);// 总金额
		String refund_fee = String.valueOf(refund_fee_long);// 退款金额
		String nonce_str = UUID.randomUUID().toString().replace("-", "");// 随机字符串
		

		SortedMap<String, String> packageParams = new TreeMap<String, String>();
		packageParams.put("appid", appid);
		packageParams.put("mch_id", mch_id);
		packageParams.put("nonce_str", nonce_str);
		packageParams.put("out_trade_no", out_trade_no);
		packageParams.put("out_refund_no", out_refund_no);
		packageParams.put("total_fee", total_fee);
		packageParams.put("refund_fee", refund_fee);
		packageParams.put("op_user_id", op_user_id);
		RequestHandler reqHandler = new RequestHandler(
				null, null);
		reqHandler.init(appid, appsecret, partnerkey);
		String sign = reqHandler.createSign(packageParams);
		String xml = "<xml>" + 
				 "<appid>" + appid + "</appid>" +
				 "<mch_id>"+ mch_id + "</mch_id>" + 
				 "<nonce_str>" + nonce_str+ "</nonce_str>" + 
				 "<sign><![CDATA[" + sign + "]]></sign>"+
				 "<out_trade_no>" + out_trade_no + "</out_trade_no>"+
				 "<out_refund_no>" + out_refund_no + "</out_refund_no>"+
				 "<total_fee>" + total_fee + "</total_fee>"+ 
				 "<refund_fee>" + refund_fee + "</refund_fee>"+
				 "<op_user_id>" + op_user_id + "</op_user_id>" + 
				 "</xml>";
		String createOrderURL = "https://api.mch.weixin.qq.com/secapi/pay/refund";
		try {
			String s= ClientCustomSSL.doRefund(createOrderURL, xml);
			System.out.println("s:"+s);
			
		Map<String,String> m=WxUtil.xmlToMap(s);
		
		String resultCode = m.get("result_code");
		if("SUCCESS".equals(resultCode)){
		return true;
		}
			//改变支付数据库中的是否退款
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * @date 2017年1月10日上午10:37:47 void
	 * @Des:退款查询
	 */
	public void querywechatRefund() {
		// 商户系统内部的退款单号，商户系统内部唯一，同一退款单号多次请求只退一笔
		String transaction_id = "656565";
		String nonce_str = "5616556165";// 随机字符串
		SortedMap<String, String> packageParams = new TreeMap<String, String>();
		packageParams.put("appid", appid);
		packageParams.put("mch_id", mch_id);
		packageParams.put("nonce_str", nonce_str);
		packageParams.put("transaction_id", transaction_id);
		RequestHandler reqHandler = new RequestHandler(
				null, null);
		reqHandler.init(appid, appsecret, partnerkey);
		String sign = reqHandler.createSign(packageParams);
		String xml = "<xml>" + 
				"<appid>" + appid + "</appid>" + 
				"<mch_id>"+ mch_id + "</mch_id>" + 
				"<nonce_str>" + nonce_str+ "</nonce_str>" + 
				"<sign><![CDATA[" + sign + "]]></sign>"+
				"<transaction_id>" + transaction_id + "</transaction_id>"+ 
				 "</xml>";
		String createOrderURL = "https://api.mch.weixin.qq.com/pay/refundquery";
		try {
			String s= ClientCustomSSL.doRefund(createOrderURL, xml);
			System.out.println("s:"+s);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
    public static String getCurrTime() {
        Date now = new Date();
        SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String s = outFormat.format(now);
        return s;
    }
	
    public static String getRandomStringByLength(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();

}}